const app = getApp();
const url_path = app.globalData.url;
Page({

  data: {
      https: "https://csb2c.fenxiangqu.cn",
      imgUrls: [
      ],
      floorImgs:[],
      indicatorDots: true,
      autoplay: true,
      interval: 3000,
      duration: 2000,
      userInfo: {},
      cookie: "",
      recom1:{},
      recom2:[],
      buying:[],
      tc:[],
      sale_list:[],
      time:"",
      block:""
  },

  /*
  加载组合套餐
   */
  captc(callback) {
    const self = this;
    var dataJson = {
      a: ""
    }
    var header = {
      'content-type': 'application/x-www-form-urlencoded',
      'Cookie': "LID=" + self.data.cookie
    }
    app.aeHttp(
      {
        method: "POST",
        api: `${url_path}xcx_combo_silid`,
        header: header,
        data: dataJson
      },
      function (res) {
        //success
        callback && callback(res)
      },
      function (err) {
        wx.showToast({
          title: '网络请求失败',
          icon: 'success',
          duration: 1000
        })
        //error
      })
  },
  addHome: function (callback) {
    var dataJson = {
        a: ""
    }
    var header = {
      'content-type': 'application/x-www-form-urlencoded',
      'Cookie': "LID=" + this.data.cookie
    }
    app.aeHttp(
      {
        method: "POST",
        api: `${url_path}xcx_all_index`,
        header: header,
        data: dataJson
      },
      function (res) {
        //success
        callback && callback(res)
      },
      function (err) {
        wx.showToast({
          title: '网络请求失败',
          icon: 'success',
          duration: 1000
        })
        //error
      })
    
  },
  onLoad (options) {
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      duration: 10000
    })
    var a = wx.getStorageSync('cookie') || [];
    var self = this;
    self.setData({
      cookie: a
    })
    self.addHome(res=>{
     
      let json = res;
      let imgurlArr = [], floorImg = [],ret=[];
      let imgurl = json.advertisement[1],
        imgObj = JSON.parse("{" + imgurl.tupian_url.split('#')[1].replace(/\./g, ",").replace(/(?:\s*['"]*)?([a-zA-Z0-9\u4e00-\u9fa5-_ %&]+)(?:['"]*\s*)?:(?:\s*['"]*)?([a-zA-Z0-9\u4e00-\u9fa5-_ %&]+)(?:['"]*\s*)?/g, "\"$1\":\"$2\"") + "}");
      if (json.carousel){
        json.carousel.map(item=>{
          imgurlArr.push({
            url: `${self.data.https}/${item.imgurl}`
          })
        })   
      }
      for (let i = 0; i < json.mod.length; i++){
        let modArray = [];
        json.mod[i].sp.map(item=>{
          if(item.imgurl != ""){
            modArray.push({
              url: `${self.data.https}${item.imgurl}`,
              id:item._id,
              iscfy:item.iscfy
            })
          }else{
            modArray.push({
              url: `${self.data.https}/upload/middle/${item.sptm}.jpg`,
              spmc: item.spmc,
              spxsj: item.spxsj.toFixed(2),
              id:item._id,
              iscfy: item.iscfy
            })
          }
        })
        floorImg.push({
          text: json.mod[i].text,
          modArray: modArray
        })
      }

      for (let i = 0; i < json.commodity.length; i++){
        if(i<=1){
          ret.push({
            id: json.commodity[i]._id,
            spmc: json.commodity[i].spmc,
            iscfy: json.commodity[i].iscfy,
            number: (+json.role1[i].jg).toFixed(2),
            src: json.commodity[i].sptm
          })
        }
      }
      let buying = [];
      for (let i = 0; i < json.buying.length; i++){
        json.buying[i][0].panic = (json.buying[i][0].panic).toFixed(2)
        buying.push(json.buying[i])
      }

      //限时抢购
      if (json.sale.length > 0) {
        var l_t;
        if (json.sale[0][0].dateSection != "") {
          l_t = new Date(json.sale[0][0].dateSection.endDateTime);
        } else {
          var _nn = new Date();
          var nowTime = new Date(_nn.getFullYear() + "/" + (_nn.getMonth() + 1) + "/" + _nn.getDate()).getTime();
          l_t = new Date(nowTime + json.sale[0][0].endTime);
        }
        self.setData({
          sale_list: json.sale,
          time: l_t
        })
        self.countDown();
      }

        self.setData({
          imgUrls: imgurlArr,
          floorImgs: floorImg,
          recom2: ret,
          recom1:{
            id: imgObj.spid,
            cfy: imgObj.cfy,
            src: imgurl.tupian
          },
          buying: buying,
          block:'animtation'
        })
        wx.hideToast()
    })

    self.captc(res=>{
      
      if (res[1].length > 0){
        self.setData({
          tc: res[1][0].config
        })
      }
    })
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },
  
  /* 点击商品跳转商品详情页 */
  bindcommp(e){
    const Target = e.currentTarget.dataset,
          self = this;
    console.log(Target)
    wx.request({
      url: "https://csb2c.fenxiangqu.cn/xcx_commodity_iscfy",
      data: {
        spid: Target.id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': "LID=" + self.data.cookie
      },
      method: "POST",
      success: function (res) {
        if (res.data) {
          if (res.data.iscfy) {
            var iscfy = res.data.iscfy;
          } else {
            var iscfy = false;
          }
          if (iscfy) {
            wx.navigateTo({
              url: '../cfcommp/cfcommp?id=' + Target.id + '&cfy=' + iscfy
            })
          } else {
            wx.navigateTo({
              url: '../commp/commp?id=' + Target.id + '&cfy=' + iscfy
            })
          }
        } else {
          wx.showToast({
            title: '抱歉！商品不存在或已下架!',
            icon: 'success',
            duration: 2000
          })
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '网络故障！',
          icon: 'success',
          duration: 1000
        })
      }
    })
  },
  /*点击限量抢购*/
  cxcomm(e){
    const data = e.currentTarget.dataset, 
      id = data.id, cx = data.cx, jg = data.jg, kc = data.kc, activityID = data.activityid;
    console.log(e.currentTarget.dataset)
      wx.navigateTo({
        url: `../cxcommp/cxcommp?id=${id}&cx=${cx}&jg=${jg}&kc=${kc}&activityid=${activityID}`
      })
  },
  
  onShow: function () {
  
  },
  xst(){
    wx.navigateTo({
      url:'../sale/sale'
    })
    wx.showLoading({
      title:"加载中"
    })
  },
  /** 
  * 倒计时函数
  */
  countDown: function () {
    var that = this;
    var obj = {}
    var countDownArr = [];

    var EndTime = new Date(that.data.time);
    var NowTime = new Date();
    //                            console.log(EndTime.getTime() - NowTime.getTime())
    var t = EndTime.getTime() - NowTime.getTime();
    var d = Math.floor(t / 1000 / 60 / 60 / 24);
    var h = Math.floor(t / 1000 / 60 / 60 % 24);
    var m = Math.floor(t / 1000 / 60 % 60);
    var s = Math.floor(t / 1000 % 60);
    if (h < 0 || m < 0 || s < 0) {
      return false
    } else {
      obj = {
        hou: this.timeFormat(h),
        min: this.timeFormat(m),
        sec: this.timeFormat(s)
      }
    }
    countDownArr.push(obj);
    setTimeout(this.countDown, 1000);
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({
      timeArr: countDownArr
    })
    if (obj.hou == "00" && obj.min == "00" && obj.sec == "00") {
      that.addHome(res=>{
        if (res.sale.length > 0) {
          console.log('aksdjkalsd')
          var l_t;
          if (res.sale[0][0].dateSection != "") {
            l_t = new Date(res.sale[0][0].dateSection.endDateTime);
          } else {
            var _nn = new Date();
            var nowTime = new Date(_nn.getFullYear() + "/" + (_nn.getMonth() + 1) + "/" + _nn.getDate()).getTime();
            l_t = new Date(nowTime + res.sale[0][0].endTime);
          }
          that.setData({
            sale_list: res.sale,
            time: l_t
          })
          that.countDown();
        }
      })
    }
  },
  timeFormat(param){
    return param < 10 ? '0' + param : param;
  }
})